import 'package:enterprise_v6_app/app/components/dialog/exit_tips.dart';
import 'package:enterprise_v6_app/app/components/dialog/submit_success.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/inspec/inspec_query_plan_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/inspec/submit_task.dart';
import 'package:enterprise_v6_app/app/data/entities/inspec/task_department_list_entity.dart';
import 'package:get/get.dart';

class ReceivedTaskController extends GetxController {


  /// 分组后的list
  List<SubmitTimeList> timeList = [];


  /// 是否点击编辑方案
  bool isClickEdit = false;

  /// 已有的方案
  List<InspecQueryPlanEntity>  alreadyPlan = [];

  /// 查询当前方案下所有任务
  List<TaskDepartmentListTaskTimeNodeTables>  queryAllTaskList = [];

  // 选择的已有方案
  int? selectAlreadyPlan;

  @override
  void onReady() {
    super.onReady();
    allTask();
    queryAlreadyPlan();
  }

  // 查询方案下所有的任务
  void allTask() async {
    final res = await HttpUtil().generateGetRequest<List<TaskDepartmentListTaskTimeNodeTables>>(
      Interface.getTaskListByUnit,
      queryParameters:  {
        'programmeId' : selectAlreadyPlan != null ? alreadyPlan[selectAlreadyPlan!].id : null,
      }
    ).execute();
    res.onSuccess((result) {
      queryAlreadyPlan();
      if(result.data != null) {
        selectAlreadyPlan = null;
        queryAllTaskList.clear();
        queryAllTaskList = result.data!;
        reLoad(queryAllTaskList);
      }
    });
  }

  /// 重新分类数据,按照时间分组
  void reLoad(List<TaskDepartmentListTaskTimeNodeTables> allTaskList) {
    timeList.clear();
    if(allTaskList.isNotEmpty) {

      // 创建一个map来存储时间和任务的对应关系
      final Map<String, SubmitTimeList> timeTaskMap = {};

      for(TaskDepartmentListTaskTimeNodeTables i in allTaskList) {
        // 提取出公共的任务
        final SubmitTask task = SubmitTask(
          id: i.id,
          time: i.startDate,
          taskName: i.troubleshootContent,
        );

        // 检查这个时间是否已经在map中+
        if(timeTaskMap.containsKey(i.startDate)) {
          // 如果在，直接添加任务到对应的时间
          timeTaskMap[i.startDate]!.tasks.add(task);
        } else {
          // 如果不在，创建一个新的SubmitTimeList并添加到map中
          timeTaskMap[i.startDate!] = SubmitTimeList(
              time: i.startDate ?? '空',
              tasks: [task]
          );
        }
      }

      // 最后将map中的值转换为list
      timeList = timeTaskMap.values.toList();
      // 根据时间排序
      timeList.sort((a, b) => int.tryParse(a.time)?.compareTo(int.tryParse(b.time)?.toInt() ?? 0) ?? 0);


    }
    update();
  }

  /// 查询已有方案
  void queryAlreadyPlan() async {
    final res = await HttpUtil().generateGetRequest<List<InspecQueryPlanEntity>>(
      Interface.getInspectionSchemeListById,
    ).execute();

    res.onSuccess((result) {
      alreadyPlan = result.data!;
    });

  }

  // 选择任务后移除任务
  void removeTask(int index,int taskIndex) async {
    if(timeList[index].tasks.isNotEmpty) {
      // timeList[index].tasks.removeAt(taskIndex);
      removeTaskSubmitData(index,taskIndex);
    } else {
      timeList.removeAt(index);
    }
    update();
  }

  // 移除任务提交数据
  void removeTaskSubmitData(int index,int taskIndex) async {
    final res = await HttpUtil().generatePostRequest(Interface.removeTask,queryParameters: {
      'id' :timeList[index].tasks[taskIndex].id,
    }).execute();
    res.onSuccess((result) {
      AppToast.show('移除成功');
      allTask();
    });
  }

  // 撤销当前方案
  void cancelCurrentPlan() async {
    Get.dialog(
        ExitTips(
          content: '撤销后，任务将不再派发，确定提交吗？',
          func: (b) {
            if(b) {
              cancelCurrentPlanRun();
            }
          },
        )
    );
  }

  // 撤销方案
  void cancelCurrentPlanRun() async {
    if(queryAllTaskList.isEmpty) {
      AppToast.showWarning('当前没有方案');
      return;
    }
    final res = await HttpUtil().generatePostRequest(Interface.delScheme,queryParameters: {
      'programmeId': queryAllTaskList[0].taskProgrammeId,
    }).execute();
    res.onSuccess((result) {
      AppToast.show('撤销成功');
    });
  }

  // 编辑当前方案
  void editCurrentPlan() async {
    isClickEdit = true;
    update();
  }

  // 方案选择
  void planSelect() {

    if(selectAlreadyPlan != null) {
      Get.back();
      allTask();
    } else {
      AppToast.showWarning('请选择方案');
    }

  }

  // 新增任务
  void addTask() {

  }

  // 取消任务
  void cancelTask() {
    isClickEdit = false;
    update();
  }

  // 提交任务
  void submitTask() {
    // todo 提交移除任务

    submitSuccess();
    cancelTask();
  }

  // 提交成功
  void submitSuccess() {
    Get.dialog(const SubmitSuccess());
  }


}
